package com.example.demo.controller;

import com.example.demo.model.Message;
import com.example.demo.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/message")
public class MessageWallController {
    @Autowired
    private MessageService messageService;

    /**
     * 发表留言
     */
    @RequestMapping("/publish")
    public String publish(Message msg){
        log.info("接收到参数：message: {}", msg);
        // 1. 检验参数
        if(!StringUtils.hasLength(msg.getFrom())
                || !StringUtils.hasLength(msg.getTo())
                || !StringUtils.hasLength(msg.getMessage())){
            return "输入参数错误";
        }
        // 2. 添加到消息列表中，并返回结果
        try{
            Integer result = messageService.publishMessage(msg);
            if(result == 0){
                return "发表留言失败，请联系管理员";
            }
            return "";
        }catch(Exception e){
            e.printStackTrace();
            return "内部错误，请联系管理员";
        }
    }

    /**
     * 显示留言
     */
    @RequestMapping("/getList")
    public List<Message> getList(){
        return messageService.getMessageList();
    }
}
